<template>
  <div class="post-detail-page">
    <div class="page-header">
      <el-button @click="router.back()">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <!-- 帖子详情 -->
    <div v-loading="loading" class="post-detail">
      <template v-if="postDetail">
        <el-card class="post-card">
          <div class="post-header">
            <div class="user-info">
              <el-avatar :size="40" :src="postDetail.userAvatar" />
              <span class="username">{{ postDetail.nickname || postDetail.username }}</span>
            </div>
            <el-tag :type="getPostTypeTag(postDetail.postType)">
              {{ postTypeMap[postDetail.postType] }}
            </el-tag>
          </div>

          <div class="post-content">
            <h1 class="post-title">{{ postDetail.title }}</h1>
            <p class="post-text">{{ postDetail.content }}</p>
          </div>

          <div class="post-footer">
            <div class="post-stats">
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ postDetail.viewCount }}
              </span>
              <span class="stat-item">
                <el-icon><ChatRound /></el-icon>
                {{ postDetail.commentCount }}
              </span>
              <span class="stat-item" @click="handleLike">
                <el-icon :class="{ 'liked': postDetail.isLiked }">
                  <Pointer />
                </el-icon>
                {{ postDetail.likeCount }}
              </span>
            </div>
            <span class="post-time">{{ formatDate(postDetail.createTime) }}</span>
          </div>
        </el-card>

        <!-- 评论区 -->
        <div class="comment-section">
          <h3>评论 ({{ total }})</h3>
          
          <!-- 评论输入框 -->
          <div class="comment-input">
            <el-input
              v-model="commentContent"
              type="textarea"
              :rows="3"
              placeholder="写下你的评论..."
            />
            <el-button
              type="primary"
              :loading="submitting"
              @click="submitComment"
            >
              发表评论
            </el-button>
          </div>

          <!-- 评论列表 -->
          <div class="comment-list">
            <div
              v-for="comment in commentList"
              :key="comment.id"
              class="comment-item"
            >
              <div class="comment-user">
                <el-avatar :size="32" :src="comment.userAvatar" />
                <span class="comment-username">{{ comment.nickname || comment.username }}</span>
                <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
              </div>
              <div class="comment-content">
                {{ comment.content }}
              </div>
              <div class="comment-actions">
                <span
                  class="action-item"
                  @click="handleReply(comment)"
                >
                  回复
                </span>
              </div>

              <!-- 递归显示评论回复 -->
              <div v-if="comment.children && comment.children.length" class="nested-replies">
                <div
                  v-for="reply in comment.children"
                  :key="reply.id"
                  class="reply-item"
                >
                  <div class="reply-user">
                    <el-avatar :size="24" :src="reply.userAvatar" />
                    <span class="reply-username">{{ reply.nickname || reply.username }}</span>
                    <span class="reply-to" v-if="reply.replyToUsername">
                      回复 
                      <span class="replied-username">{{ reply.replyToNickname || reply.replyToUsername }}</span>
                    </span>
                    <span class="reply-time">{{ formatDate(reply.createTime) }}</span>
                  </div>
                  <div class="reply-content">
                    {{ reply.content }}
                  </div>
                  <div class="reply-actions">
                    <span class="action-item" @click="handleReply(reply)">回复</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-container" v-if="total > 0">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="total"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </template>
    </div>

    <!-- 回复对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      :title="'回复 ' + (currentComment?.nickname || currentComment?.username || '')"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-input
        v-model="replyContent"
        type="textarea"
        :rows="3"
        :placeholder="'回复 @' + (currentComment?.nickname || currentComment?.username || '') + '...'"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitting"
            @click="submitReply"
          >
            回复
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, View, ChatRound, Pointer } from '@element-plus/icons-vue'
import {
  getPostDetail,
  getCommentList,
  createComment,
  replyComment,
  deleteComment,
  likePost,
  unlikePost
} from '@/api/community'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()

// 帖子类型映射
const postTypeMap = {
  0: '普通帖子',
  1: '经验分享',
  2: '提问求助',
  3: '热门话题'
}

// 获取帖子类型对应的标签类型
const getPostTypeTag = (type) => {
  const tagMap = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return tagMap[type] || 'info'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '--'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 页面数据
const loading = ref(false)
const postDetail = ref(null)
const commentList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const commentContent = ref('')
const submitting = ref(false)

// 回复相关
const replyDialogVisible = ref(false)
const replyContent = ref('')
const currentComment = ref(null)

// 获取帖子详情
const fetchPostDetail = async () => {
  loading.value = true
  try {
    const res = await getPostDetail(route.params.id)
    if (res) {
      postDetail.value = res
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    ElMessage.error('获取帖子详情失败')
  } finally {
    loading.value = false
  }
}

// 构建二级评论树
const buildCommentTree = (comments) => {
  const commentMap = new Map()
  const rootComments = []

  // 首先创建所有评论的映射
  comments.forEach(comment => {
    commentMap.set(comment.id, { ...comment, children: [] })
  })

  // 构建二级评论结构
  comments.forEach(comment => {
    const node = commentMap.get(comment.id)
    if (comment.parentId) {
      // 获取父评论
      const parent = commentMap.get(comment.parentId)
      if (parent) {
        // 如果父评论本身就是回复，则将当前评论添加到原始父评论的children中
        if (parent.parentId) {
          const rootParent = commentMap.get(parent.parentId)
          if (rootParent) {
            rootParent.children.push(node)
          }
        } else {
          // 如果父评论是一级评论，则直接添加到其children中
          parent.children.push(node)
        }
      }
    } else {
      rootComments.push(node)
    }
  })

  return rootComments
}

// 获取评论列表
const fetchCommentList = async () => {
  try {
    const params = {
      postId: route.params.id,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    const res = await getCommentList(params)
    if (res) {
      commentList.value = buildCommentTree(res.records)
      total.value = res.total
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  submitting.value = true
  try {
    await createComment({
      postId: route.params.id,
      content: commentContent.value.trim()
    })
    ElMessage.success('评论成功')
    commentContent.value = ''
    fetchCommentList()
    if (postDetail.value) {
      postDetail.value.commentCount++
    }
  } catch (error) {
    console.error('评论失败:', error)
    ElMessage.error('评论失败')
  } finally {
    submitting.value = false
  }
}

// 提交回复
const submitReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  submitting.value = true
  try {
    const replyData = {
      postId: route.params.id,
      parentId: currentComment.value.id,
      content: replyContent.value.trim(),
      replyToUserId: currentComment.value.userId,
      replyToUsername: currentComment.value.username
    }
    await replyComment(replyData)
    ElMessage.success('回复成功')
    replyContent.value = ''
    replyDialogVisible.value = false
    fetchCommentList()
    if (postDetail.value) {
      postDetail.value.commentCount++
    }
  } catch (error) {
    console.error('回复失败:', error)
    ElMessage.error('回复失败')
  } finally {
    submitting.value = false
  }
}

// 删除评论
const handleDeleteComment = async (comment) => {
  try {
    await deleteComment(comment.id)
    ElMessage.success('删除成功')
    fetchCommentList()
    if (postDetail.value) {
      postDetail.value.commentCount--
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 处理回复
const handleReply = (comment) => {
  currentComment.value = comment
  replyContent.value = ''
  replyDialogVisible.value = true
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchCommentList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchCommentList()
}

// 点赞/取消点赞
const handleLike = async () => {
  try {
    if (postDetail.value.isLiked) {
      await unlikePost(postDetail.value.id)
      postDetail.value.likeCount--
    } else {
      await likePost(postDetail.value.id)
      postDetail.value.likeCount++
    }
    postDetail.value.isLiked = !postDetail.value.isLiked
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

onMounted(() => {
  fetchPostDetail()
  fetchCommentList()
})
</script>

<style scoped>
.post-detail-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 24px;
}

.post-card {
  margin-bottom: 24px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.post-content {
  margin-bottom: 24px;
}

.post-title {
  margin: 0 0 16px;
  font-size: 24px;
  color: #303133;
  font-weight: 600;
}

.post-text {
  margin: 0;
  color: #606266;
  line-height: 1.8;
  font-size: 16px;
  white-space: pre-wrap;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
}

.post-stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  font-size: 14px;
}

.stat-item:hover {
  color: #409eff;
}

.liked {
  color: #409eff;
}

.post-time {
  font-size: 14px;
}

.comment-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.comment-section h3 {
  margin: 0 0 20px;
  font-size: 18px;
  color: #303133;
}

.comment-input {
  margin-bottom: 24px;
}

.comment-input :deep(.el-textarea__inner) {
  background: #f5f7fa;
  border: none;
  padding: 12px;
}

.comment-input .el-button {
  margin-top: 12px;
  float: right;
}

.comment-list {
  margin-top: 24px;
}

.comment-item {
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-user {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.comment-username {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-content {
  margin: 8px 0;
  color: #606266;
  line-height: 1.6;
}

.comment-actions {
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
  cursor: pointer;
}

.action-item:hover {
  color: #409eff;
}

.reply-list {
  margin-top: 12px;
  margin-left: 48px;
  background: #f8f9fa;
  border-radius: 4px;
  padding: 12px;
}

.reply-item {
  padding: 8px 0;
}

.reply-item:not(:last-child) {
  border-bottom: 1px solid #ebeef5;
}

.reply-user {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.reply-username {
  font-weight: 500;
  color: #303133;
}

.reply-to {
  color: #909399;
  font-size: 14px;
}

.replied-username {
  color: #409eff;
  font-weight: 500;
}

.reply-content {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin-left: 32px;
}

.reply-actions {
  margin-top: 8px;
  margin-left: 32px;
  display: flex;
  gap: 16px;
}

.reply-time {
  color: #909399;
  font-size: 12px;
}

.action-item {
  color: #909399;
  font-size: 13px;
  cursor: pointer;
}

.action-item:hover {
  color: #409eff;
}

.liked {
  color: #409eff;
}

.nested-replies {
  margin-top: 12px;
  margin-left: 48px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.nested-replies .nested-replies {
  background: #fff;
  border: 1px solid #ebeef5;
  margin-left: 36px;
}

.nested-replies .reply-item {
  padding: 8px 0;
}

.nested-replies .reply-item:not(:last-child) {
  border-bottom: 1px solid #ebeef5;
}

.reply-to {
  color: #909399;
  font-size: 14px;
  margin: 0 4px;
}

.replied-username {
  color: #409eff;
  font-weight: 500;
}
</style> 